<?php

namespace App\Http\Controllers;

use App\Models\WechatTemplateMsg;
use EasyWeChat\Factory;

class SendController extends Controller
{
    public function tplMsg()
    {
        $flowData['totalFlow'] = 2;
        $sendData = [
            'thing2' => '王邦德剩余流量通知',
            'thing3' => '总流量：' . $flowData['totalFlow'] . ' M',
            'time4'  => date('Y-m-d H:i:s'),
        ];

        $openids = [
            'o7tUYs6mBNLBl9Vtl0hVxZyv8fYo',
        ];
        $tplId = 'gv8Vd2WJDdsqFMTk7KIaayhlKl8chCb8K1To5yQZdTg';
        $config = config('wechat.offical');
        $app = Factory::officialAccount($config);
        foreach ($openids as $openid) {
            $req = [
                'touser'      => $openid,
                'template_id' => $tplId,
                'url'         => 'http://baoming.xywlk.com/gprssearch.aspx?openid=ou00Qs4HW5q_2Sz6VO9zxoudDCVg',
                'data'        => $sendData,
            ];
            $res = $app->template_message->send($req);
            //$res = json_decode($result, true);
            $state = 2;
            if (isset($res['errcode']) && $res['errcode'] == 0) {
                $state = 1;
            }
            WechatTemplateMsg::query()->create([
                'tpl_id'      => $tplId,
                'tpl_name'    => '测试',
                'tpl_content' => $req,
                'openid'      => $openid,
                'name'        => '',
                'result'      => $res ?: [],
                'state'       => $state,
                'msg'         => ($res['errmsg'] ?? '') ?: '',
            ]);
        }
    }
}
